package com.yin.waimai.controller;

import com.yin.waimai.dto.OrderDTO;
import com.yin.waimai.enums.OrderStatus;
import com.yin.waimai.service.DeliveryPersonService;
import com.yin.waimai.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员订单操作控制器
 * 提供管理员专用的订单操作功能
 */
@RestController
@RequestMapping("/api/v1/admin/orders")
// @PreAuthorize("hasRole('ADMIN')") // 临时注释掉这一行，与现有AdminController保持一致
public class AdminOrderController {

    private static final Logger log = LoggerFactory.getLogger(AdminOrderController.class);

    private final OrderService orderService;
    private final DeliveryPersonService deliveryPersonService;

    @Autowired
    public AdminOrderController(OrderService orderService, DeliveryPersonService deliveryPersonService) {
        this.orderService = orderService;
        this.deliveryPersonService = deliveryPersonService;
    }

    /**
     * 管理员修改订单状态
     * @param orderNumber 订单号
     * @param requestBody 包含新状态的请求体
     * @return 更新后的订单
     */
    @PutMapping("/{orderNumber}/status")
    public ResponseEntity<?> updateOrderStatus(
            @PathVariable String orderNumber,
            @RequestBody Map<String, String> requestBody) {
        
        String newStatusStr = requestBody.get("status");
        String location = requestBody.get("location");
        String description = requestBody.get("description");
        
        if (newStatusStr == null) {
            return ResponseEntity.badRequest().body("Status is required");
        }
        
        try {
            OrderStatus newStatus = OrderStatus.valueOf(newStatusStr);
            
            // 使用"ADMIN"作为操作员标识
            OrderDTO updatedOrder = orderService.updateOrderStatusAndAddTrace(
                    orderNumber, 
                    newStatus, 
                    "ADMIN", 
                    location != null ? location : "管理后台", 
                    description != null ? description : "管理员手动更新状态为" + newStatus.getDescription()
            );
            
            log.info("Admin updated order {} status to {}", orderNumber, newStatus);
            return ResponseEntity.ok(updatedOrder);
            
        } catch (IllegalArgumentException e) {
            log.error("Invalid order status: {}", newStatusStr, e);
            return ResponseEntity.badRequest().body("Invalid order status: " + newStatusStr);
        } catch (Exception e) {
            log.error("Error updating order status", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error updating order status: " + e.getMessage());
        }
    }

    /**
     * 管理员手动分配配送员
     * @param orderNumber 订单号
     * @param requestBody 包含配送员ID的请求体
     * @return 更新后的订单
     */
    @PutMapping("/{orderNumber}/assign")
    public ResponseEntity<?> assignDeliveryPerson(
            @PathVariable String orderNumber,
            @RequestBody Map<String, String> requestBody) {
        
        String deliveryPersonId = requestBody.get("deliveryPersonId");
        
        if (deliveryPersonId == null || deliveryPersonId.isEmpty()) {
            return ResponseEntity.badRequest().body("Delivery person ID is required");
        }
        
        try {
            // 检查配送员是否存在
            boolean deliveryPersonExists = deliveryPersonService.existsById(deliveryPersonId);
            if (!deliveryPersonExists) {
                return ResponseEntity.badRequest().body("Delivery person not found with ID: " + deliveryPersonId);
            }
            
            // 使用"ADMIN"作为操作员标识
            OrderDTO updatedOrder = orderService.assignDeliveryPerson(orderNumber, deliveryPersonId, "ADMIN");
            
            log.info("Admin assigned delivery person {} to order {}", deliveryPersonId, orderNumber);
            return ResponseEntity.ok(updatedOrder);
            
        } catch (Exception e) {
            log.error("Error assigning delivery person", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error assigning delivery person: " + e.getMessage());
        }
    }

    /**
     * 管理员自动分配最近的配送员
     * @param orderNumber 订单号
     * @return 更新后的订单
     */
    @PutMapping("/{orderNumber}/auto-assign")
    public ResponseEntity<?> autoAssignDeliveryPerson(@PathVariable String orderNumber) {
        try {
            // 使用"ADMIN"作为操作员标识
            OrderDTO updatedOrder = orderService.autoAssignDeliveryPerson(orderNumber, "ADMIN");
            
            if (updatedOrder.getDeliveryPersonId() != null) {
                log.info("Admin auto-assigned delivery person {} to order {}", 
                        updatedOrder.getDeliveryPersonId(), orderNumber);
                return ResponseEntity.ok(updatedOrder);
            } else {
                log.warn("No available delivery person to auto-assign for order {}", orderNumber);
                Map<String, String> response = new HashMap<>();
                response.put("message", "No available delivery person to assign");
                response.put("orderNumber", orderNumber);
                return ResponseEntity.ok(response);
            }
            
        } catch (Exception e) {
            log.error("Error auto-assigning delivery person", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error auto-assigning delivery person: " + e.getMessage());
        }
    }
}